import axios from 'axios';
import qs from 'qs';
import url from './baseUrl';
import { getApiError } from './responseStatus';

//axios配置
// axios.defaults.withCredentials = true;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.timeout = 50000;
axios.defaults.baseURL = url.base;

//request 拦截器
axios.interceptors.request.use(
	(config) => {
		// config.data = JSON.stringify(config.data);
		// config.headers = {
		// 	'Content-Type': 'application/x-www-form-urlencoded'
		// };
		return config;
	},
	(error) => {
		return Promise.reject(error);
	}
);
//response 拦截器
axios.interceptors.response.use(
	(response) => {
		return response;
	},
	(err) => {
		// 对响应错误做点什么
		if (err && err.response) {
			let errorMsg = getApiError(err.response.status);
			console.log(errorMsg);
		}
		return Promise.resolve(err.response);
	}
);

const request = ({ method, url, data }) => {
	const config = {};
	if (method === 'get') {
		config.params = data;
	} else {
		config.data = data instanceof FormData ? data : qs.stringify(data);
	}

	return new Promise((resolve, reject) => {
		axios({ method, url, ...config }).then(
			(response) => {
				resolve(response);
			},
			(err) => {
				reject(err);
			}
		);
	});
};
export default request;
